package com.demo.controller;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: lixiaodong
 * @Description: 线程测试类
 * @Date: 2022/9/17 11:46
 */
public class SellTicket implements Runnable {

    int ticket = 50;// 剩余票数
    ReentrantLock lock = new ReentrantLock();
    Object ob = new Object();
    @Override
    public void run() {
        //while循环实现
        while (true) {
            try {
              lock.lock();
                synchronized (this) {
                    if (ticket > 0) {
                        sell();
                    } else {
                        break;
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }

    public synchronized void sell() {
        try {
//            Thread.sleep(100);
            ob.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "出售第 " + ticket + " 张车票");
        ticket--;
    }


//    public static void main(String[] args) {
//        SellTicket sellTicket = new SellTicket();
//        Thread thread1 = new Thread(sellTicket, "窗口1");
//        thread1.start();
//        Thread thread2 = new Thread(sellTicket, "窗口2");
//        thread2.start();
//        Thread thread3 = new Thread(sellTicket, "窗口3");
//        thread3.start();
//    }

}
